'use strict';

const {
	wxmpapi
} = require('use-api');

const db = uniCloud.database();
const dbcmd = db.command;

exports.main = async (event, context) => {
	let response = {
		code: 0,
		datas: {
			received: {
				count: 0
			},
			completed: {
				count: 0
			},
			aftersale: {
				count: 0
			},
			coupon: {
				count: 0
			},
			lotteryPool: {
				count: 0
			},
			fxsOrderRollback: {
				count: 0
			},
			syncWxDelivery: {
				count1: 0,
				count2: 0
			}
		}
	};
	const ip = context.CLIENTIP;
	const orderParameterRes = await db.collection('usemall-order-parameter')
		.field({
			overdue_minute_cancel_order: true,
			overdue_day_receiving: true,
			overdue_day_close_evaluated: true,
			overdue_day_close_aftersale: true,
		})
		.limit(1)
		.get();
	const [orderParameter] = orderParameterRes.data;

	// 发货后 超过 7天，自动确认收货
	response.datas.received.count = await doReceivedOrder(ip, orderParameter);
	
	// 收货后 超过 15天，关闭评价订单改为已完成
	response.datas.completed.count = await doCompletedOrder(ip, orderParameter);
	
	// 收货后 超过 15天，关闭售后入口，并奖励积分
	response.datas.aftersale.count = await doAfterSaleOrder(ip, orderParameter);
	
	// 处理已过期优惠券
	response.datas.coupon.count = await doExpireCoupon(ip);
	
	// 每日生成抽奖池数据
	response.datas.lotteryPool.count = await doLotteryPool(ip);
	
	// 处理已付款 - 发生退款操作的未结算分销订单
	response.datas.fxsOrderRollback.count = await doFxsOrderRollback(ip);
	
	// 同步微信虚拟订单发货（微信小程序充值支付、开通会员等支付场景）
	// 1微信小程序充值支付场景
	response.datas.syncWxDelivery.count1 = await doSyncWxDelivery1(ip);
	// 2微信小程序支付开通会员场景
	response.datas.syncWxDelivery.count2 = await doSyncWxDelivery2(ip);
	
	//返回数据给客户端
	return response;
};

// 发货后 超过 7天，自动确认收货
// overdue_day_receiving
const doReceivedOrder = async (ip, orderParameter) => {
	const receivedOrderTime = orderParameter.overdue_day_receiving || 7;
	let count = 0;
	let receivedRes = {};
	do {
		// 订单确认收货
		receivedRes = await receivedOrder(ip, receivedOrderTime);
		count += receivedRes.count;
	} while (receivedRes.count >= 300)
	
	return count;
}
const receivedOrder = async (ip, receivedOrderTime = 7) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	// 针对之前的老数据，可以使用 last_modify_time 替换 deliver_time，右键 order-job 运行-本地云函数 执行一次
	// last_modify_time: dbcmd.lte(nowdate - receivedOrderTime * 24 * 60 * 60 * 1000)
	// deliver_time: dbcmd.lte(nowdate - receivedOrderTime * 24 * 60 * 60 * 1000)
	const orderRes = await db.collection('usemall-order')
		.where({
			state: '待收货',
			// 发货时间
			deliver_time: dbcmd.lte(nowdate - receivedOrderTime * 24 * 60 * 60 * 1000)
		})
		.field({
			order_actural_paid: true,
			order_id: true,
			is_fxs: true,
			is_settlement: true,
			settlement_type: true,
			order_fxs_uid: true,
			order_fxs_amount: true,
			order_fxs_uid2: true,
			order_fxs_amount2: true,
			order_member_name: true,
			order_member_openid: true,
			order_member_headimg: true,
			order_info: true,
			order_goods_cnt: true,
			create_uid: true
		})
		.limit(300)
		.get();
	
	if (orderRes.data && orderRes.data.length > 0) {
		res.count = orderRes.data.length;
	
		const orderIds = [];
		const orderLogs = [];
		
		for (let i = 0; i < orderRes.data.length; i++) {
			let order = orderRes.data[i];
			let orderUpdate = {
				state: '待评价',
				
				// 收货时间
				received_time: nowdate,
				received_uid: 'job-day',
				received_uname: 'job-day',
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			}
			
			// 结算类型
			order.settlement_type = order.settlement_type || 1;
			// 分销订单
			if (order.is_fxs == '是' && order.is_settlement == '否' && order.settlement_type == 1) {
				if (order.order_fxs_uid && order.order_fxs_amount) {
					// 1. 分销商可提现金额
					await db.collection('usemall-distributor').doc(order.order_fxs_uid).update({
						fxs_unsettled_amount: db.command.inc(-order.order_fxs_amount),
						fxs_cashout_amount: db.command.inc(order.order_fxs_amount),
						version: db.command.inc(1),
				
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
					// 2. 分销记录状态 已结算
					await db.collection('usemall-distributor-record').where({
						fxs_uid: order.order_fxs_uid,
						order_id: order.order_id
					}).update({
						version: db.command.inc(1),
						state: '已结算',
				
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
				
					// 3. 分销操作日志
					await db.collection('usemall-distributor-log').add({
						fxs_uid: order.order_fxs_uid,
						oper_content: `结算订单[+${order.order_id}]收益`,
						oper_type: '下单收益',
						oper_ip: ip,
						remark: `下级会员[${order.order_member_name}]下单[+${order.order_fxs_amount / 100}]`,
						version: 1,
						is_delete: 0,
						create_uid: 'job-day',
						create_time: nowdate
					});
				}
			
				if (order.order_fxs_uid2 && order.order_fxs_amount2) {
					// 1. 上上级分销商可提现金额
					await db.collection('usemall-distributor').doc(order.order_fxs_uid2).update({
						fxs_unsettled_amount: db.command.inc(-order.order_fxs_amount2),
						fxs_cashout_amount: db.command.inc(order.order_fxs_amount2),
						version: db.command.inc(1),
					
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
					// 2. 上上级分销记录状态 已结算
					await db.collection('usemall-distributor-record').where({
						fxs_uid: order.order_fxs_uid2,
						order_id: order.order_id
					}).update({
						version: db.command.inc(1),
						state: '已结算',
					
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
					
					// 3. 上上级分销操作日志
					await db.collection('usemall-distributor-log').add({
						fxs_uid: order.order_fxs_uid2,
						oper_content: `结算订单[+${order.order_id}]收益`,
						oper_type: '下单收益',
						oper_ip: ip,
						remark: `下下级会员[${order.order_member_name}]下单[+${order.order_fxs_amount2 / 100}]`,
						version: 1,
						is_delete: 0,
						create_uid: 'job-day',
						create_time: nowdate
					});
				}
				
				// 4. 分销订单已结算
				orderUpdate.is_settlement = '是';
				orderUpdate.settlement_time = nowdate;
			}
			
			// 修改订单为待评价
			await db.collection('usemall-order')
				.doc(order._id)
				.update(orderUpdate);
				
			orderLogs.push({
				order_id: order.order_id,
				log_type: '确认收货',
				remark: `待收货超过 ${receivedOrderTime} 天，自动确认收货`,
				current_state: '待评价',
				prev_state: '待收货',
				ip: ip,
				is_delete: 0,
				create_uid: 'job-day',
				create_time: nowdate
			});
		}
	
		res.addLogRes = await db.collection('usemall-order-log').add(orderLogs);
	}
	
	return res;
}

// 收货后 超过 15天，关闭评价订单改为已完成
// overdue_day_close_evaluated
const doCompletedOrder = async (ip, orderParameter) => {
	const configTime = orderParameter.overdue_day_close_evaluated || 7;
	let count = 0;
	let res = {};
	do {
		// 订单已完成
		res = await completedOrder(ip, configTime);
		count += res.count;
	} while (res.count >= 300)
	
	return count;
}
const completedOrder = async (ip, configTime = 15) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	const orderRes = await db.collection('usemall-order')
		.where({
			state: '待评价',
			// 收货时间 超过 15天
			received_time: dbcmd.lte(nowdate - configTime * 24 * 60 * 60 * 1000)
		})
		.field({
			order_id: true,
			create_uid: true,
			order_return_integral: true
		})
		.limit(300)
		.get();
	
	if (orderRes.data && orderRes.data.length > 0) {
		res.count = orderRes.data.length;
		
		const orderIds = [];
		const orderLogs = [];
		
		for (let i = 0; i < orderRes.data.length; i++) {
			let order = orderRes.data[i];
			
			orderIds.push(order.order_id);
			orderLogs.push({
				order_id: order.order_id,
				log_type: '订单已完成',
				remark: `收货后超过 ${configTime} 天，关闭评价订单改为已完成`,
				current_state: '已完成',
				prev_state: '待评价',
				ip: ip,
				is_delete: 0,
				create_uid: 'job-day',
				create_time: nowdate
			});
		}
	
		// 修改订单为已完成
		res.updateRes = await db.collection('usemall-order')
			.where({
				order_id: dbcmd.in(orderIds)
			})
			.update({
				state: '已完成',
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			})
		
		res.addLogRes = await db.collection('usemall-order-log').add(orderLogs);
	}
	
	return res;
}

// 收货后 超过 15天，关闭售后入口
// overdue_day_close_aftersale
const doAfterSaleOrder = async (ip, orderParameter) => {
	const configTime = orderParameter.overdue_day_close_aftersale || 7;
	let count = 0;
	let res = {};
	do {
		// 订单关闭售后入口
		res = await afterSaleOrder(ip, configTime);
		count += res.count;
	} while (res.count >= 300)
	
	return count;
}
const afterSaleOrder = async (ip, configTime = 15) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	const orderRes = await db.collection('usemall-order')
		.where({
			// 0未售后 1售后中 2已售后 99禁止售后
			aftersale_state: 0,
			// 收货时间超过 15天
			received_time: dbcmd.lte(nowdate - configTime * 24 * 60 * 60 * 1000)
		})
		.field({
			state: true,
			order_id: true,
			is_fxs: true,
			is_settlement: true,
			settlement_type: true,
			order_fxs_uid: true,
			order_fxs_amount: true,
			order_fxs_uid2: true,
			order_fxs_amount2: true,
			order_member_name: true,
			order_member_openid: true,
			order_member_headimg: true,
			create_uid: true,
			order_return_integral: true
		})
		.limit(300)
		.get();
	
	if (orderRes.data && orderRes.data.length > 0) {
		res.count = orderRes.data.length;
	
		const orderIds = [];
		const orderLogs = [];
		
		const nowtime = toDateUTC8(new Date());
		const time = `${nowtime.getFullYear()}-${(nowtime.getMonth() + 1+ '').padStart(2, '0')}-${(nowtime.getDate()+ '').padStart(2, '0')} ${(nowtime.getHours()+ '').padStart(2, '0')}:${(nowtime.getMinutes()+ '').padStart(2, '0')}`;
		
		for (let i = 0; i < orderRes.data.length; i++) {
			let order = orderRes.data[i];
			let orderUpdate = {
				aftersale_state: 99,
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			}
			
			// 奖励下单人积分
			let uid = order.create_uid;
			let integral = order.order_return_integral;
			
			if (integral > 0) {
				await db.collection('usemall-member').doc(uid).update({
					member_integral: db.command.inc(integral),
					member_integral_surplus: db.command.inc(integral),
					member_integral_total: db.command.inc(integral)
				});
				
				// 记录积分数据
				await db.collection('usemall-integral-record').add({
					member_id: uid,
					member_uid: uid,
					integral: integral,
					type: '收入',
					source: '下单',
					order_id: order.order_id,
					goods_id: '',
					remark: `+${integral} 积分`,
					state: '正常',
					is_delete: 0,
					time: time,
					create_time: nowdate,
					create_uid: uid,
					create_uname: 'job-day'
				});
				
				// 积分日志
				await db.collection('usemall-integral-log').add({
					member_id: uid,
					member_uid: uid,
					integral: integral,
					ip: ip,
					type: '下单',
					content: `+${integral} 积分`,
					remark: `下单 +${integral} 积分`,
					state: '正常',
					is_delete: 0,
					time: time,
					create_time: nowdate,
					create_uid: uid,
					create_uname: 'job-day'
				});
			}
			
			// 结算类型
			order.settlement_type = order.settlement_type || 1;
			// 分销订单
			if (order.is_fxs == '是' && order.is_settlement == '否' && order.settlement_type == 2) {
				if (order.order_fxs_uid && order.order_fxs_amount) {
					// 1. 分销商可提现金额
					await db.collection('usemall-distributor').doc(order.order_fxs_uid).update({
						fxs_unsettled_amount: db.command.inc(-order.order_fxs_amount),
						fxs_cashout_amount: db.command.inc(order.order_fxs_amount),
						version: db.command.inc(1),
				
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
					// 2. 分销记录状态 已结算
					await db.collection('usemall-distributor-record').where({
						fxs_uid: order.order_fxs_uid,
						order_id: order.order_id
					}).update({
						version: db.command.inc(1),
						state: '已结算',
				
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
				
					// 3. 分销操作日志
					await db.collection('usemall-distributor-log').add({
						fxs_uid: order.order_fxs_uid,
						oper_content: `结算订单[+${order.order_id}]收益`,
						oper_type: '下单收益',
						oper_ip: ip,
						remark: `下级会员[${order.order_member_name}]下单[+${order.order_fxs_amount / 100}]`,
						version: 1,
						is_delete: 0,
						create_uid: 'job-day',
						create_time: nowdate
					});
				}
			
				if (order.order_fxs_uid2 && order.order_fxs_amount2) {
					// 1. 上上级分销商可提现金额
					await db.collection('usemall-distributor').doc(order.order_fxs_uid2).update({
						fxs_unsettled_amount: db.command.inc(-order.order_fxs_amount2),
						fxs_cashout_amount: db.command.inc(order.order_fxs_amount2),
						version: db.command.inc(1),
					
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
					// 2. 上上级分销记录状态 已结算
					await db.collection('usemall-distributor-record').where({
						fxs_uid: order.order_fxs_uid2,
						order_id: order.order_id
					}).update({
						version: db.command.inc(1),
						state: '已结算',
					
						last_modify_uid: 'job-day',
						last_modify_time: nowdate
					});
					
					// 3. 上上级分销操作日志
					await db.collection('usemall-distributor-log').add({
						fxs_uid: order.order_fxs_uid2,
						oper_content: `结算订单[+${order.order_id}]收益`,
						oper_type: '下单收益',
						oper_ip: ip,
						remark: `下下级会员[${order.order_member_name}]下单[+${order.order_fxs_amount2 / 100}]`,
						version: 1,
						is_delete: 0,
						create_uid: 'job-day',
						create_time: nowdate
					});
				}
				
				// 4. 分销订单已结算
				orderUpdate.is_settlement = '是';
				orderUpdate.settlement_time = nowdate;
			}
			
			// 修改订单为禁止售后
			await db.collection('usemall-order')
				.doc(order._id)
				.update(orderUpdate);
			
			orderLogs.push({
				order_id: order.order_id,
				log_type: '关闭售后',
				remark: `收货后超过 ${configTime} 天，关闭售后入口`,
				current_state: order.state,
				prev_state: order.state,
				ip: ip,
				is_delete: 0,
				create_uid: 'job-day',
				create_time: nowdate
			});
		}
	
		res.addLogRes = await db.collection('usemall-order-log').add(orderLogs);
	}
	
	return res;
}


// 处理已过期优惠券
const doExpireCoupon = async (ip) => {
	let count = 0;
	let res = {};
	do {
		// 已过期优惠券
		res = await expireCoupon(ip);
		count += res.count;
	} while (res.count >= 300)
	
	return count;
}
const expireCoupon = async (ip) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	const couponRes = await db.collection('usemall-marketing-coupon-rule')
		.where({
			is_delete: 0,
			// 状态 待激活|运营中|已过期
			state: '运营中',
			// 优惠券结束时间
			end_time: dbcmd.lte(nowdate)
		})
		.limit(300)
		.get();
	
	if (couponRes.data && couponRes.data.length > 0) {
		res.count = couponRes.data.length;
	
		const couponIds = couponRes.data.map(x => x._id);

		// 修改优惠券 rule 为已过期
		res.updateRes = await db.collection('usemall-marketing-coupon-rule')
			.where({
				_id: dbcmd.in(couponIds)
			})
			.update({
				state: '已过期',
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			})
		
		// 批量修改优惠券为已过期
		res.updateRes = await db.collection('usemall-marketing-coupon')
			.where({
				coupon_id: dbcmd.in(couponIds),
				// 状态 待领取|已领取|已使用|已过期
				state: dbcmd.in(['待领取', '已领取'])
			})
			.update({
				state: '已过期',
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			})
	}
	
	return res;
}


// 每日生成抽奖池数据
const doLotteryPool = async (ip) => {
	// 清理已有抽奖池数据
	const removeRes = await db.collection('usemall-lottery-pool').where({
		_id: db.command.exists(true)
	}).remove();
	console.log('清理已有抽奖池数据', removeRes.result);
	
	// 查询抽奖配置表
	const lotteryParameterRes = await db.collection('usemall-lottery-parameter')
		.limit(1)
		.get();
		
	const [lotteryParameter] = lotteryParameterRes.data;
	console.log('每日生成抽奖池数据', lotteryParameter);
	
	if (lotteryParameter.state === 0) {
		// 抽奖功能未启用
		console.log('抽奖功能未启用');
		return 0;
	}
	
	const prizes = lotteryParameter.prizes || [];
	if (!prizes.length) {
		// 抽奖功能未启用
		console.log('奖品未配置');
		return 0;
	}
	console.log('奖品数据', prizes);
	
	const nowdate = Date.now();
	const nowtime = toDateUTC8(new Date());
	const yymmdd = `${nowtime.getFullYear()}-${(nowtime.getMonth() + 1+ '').padStart(2, '0')}-${(nowtime.getDate()+ '').padStart(2, '0')}`;
	
	let idx = 0;
	const prizePool = [];
	// 按每项奖品权重生成奖品池
	for (var i = 0; i < prizes.length; i++) {
		const prize = prizes[i];
		
		for (var j = 0; j < prize.weight; j++) {
			idx++;
			prizePool.push({
				lottery_id: prize.id,
				idx: idx,
				yymmdd: yymmdd,
				state: 0,
				create_time: nowdate,
				create_uid: '',
				create_uname: 'job-day'
			});
		}
	}
	
	const count = prizePool.length;
	if (!count) {
		console.log('生成抽奖池数据', count);
		return count;
	}
	
	if (prizePool.length) {
		const res = await db.collection('usemall-lottery-pool').add(prizePool);
		console.log('已生成抽奖池数据', res.ids.length);
	} 
	
	return count;
}


// 处理已付款 - 发生退款操作的未结算分销订单
const doFxsOrderRollback = async (ip) => {
	let count = 0;
	let res = {};
	do {
		// 处理分销订单 - 单商品订单
		res = await fxsOrderRollback1(ip);
		count += res.count;
	} while (res.count >= 300)
	
	do {
		// 处理分销订单 - 多商品订单
		res = await fxsOrderRollback2(ip);
		count += res.count;
	} while (res.count >= 300)
	
	return count;
}
// 单商品订单
const fxsOrderRollback1 = async (ip) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	const orderRes = await db.collection('usemall-order')
		.aggregate()
		.match({
			// 已付款
			order_pay_state: '已付款',
			// 已退款
			order_refund_state: '已退款',
			// 分销订单
			is_fxs: '是',
			// 未结算
			is_settlement: '否',
			// 订单数量
			order_total_cnt: db.command.eq(1),
			// 佣金大于0
			order_fxs_amount: db.command.gt(0),
			// 未回滚
			is_fxs_rollback: db.command.exists(false)
		})
		.project({
			order_id: true,
			state: true,
			order_pay_state: true,
			order_refund_state: true,
			create_uid: true,
			is_fxs: true,
			is_settlement: true,
			order_fxs_uid: true,
			order_fxs_amount: true,
			order_fxs_uid2: true,
			order_fxs_amount2: true,
			order_aftersale: true,
			aftersale_state: true
		})
		.limit(300)
		.end();
	
	if (orderRes.data && orderRes.data.length > 0) {
		res.count = orderRes.data.length;
	
		const orderIds = [];
		
		for (let i = 0; i < orderRes.data.length; i++) {
			let order = orderRes.data[i];
			
			orderIds.push(order.order_id);
			
			// 下单人
			let uid = order.create_uid;
			
			if (order.order_fxs_uid && order.order_fxs_amount) {
				// 上级
				
				// 1. 扣减待结佣金
				await db.collection('usemall-distributor').doc(order.order_fxs_uid).update({
					fxs_unsettled_amount: db.command.inc(-order.order_fxs_amount)
				});
				// 2. 修改佣金记录的状态
				await db.collection('usemall-distributor-record').where({
					fxs_uid: order.order_fxs_uid,
					order_id: order.order_id,
					create_uid: uid
				}).update({
					state: '已退款',
					version: db.command.inc(1)
				});
			}
			
			if (order.order_fxs_uid2 && order.order_fxs_amount2) {
				// 上上级
				
				// 1. 扣减待结佣金
				await db.collection('usemall-distributor').doc(order.order_fxs_uid2).update({
					fxs_unsettled_amount: db.command.inc(-order.order_fxs_amount2)
				});
				// 2. 修改佣金记录的状态
				await db.collection('usemall-distributor-record').where({
					fxs_uid: order.order_fxs_uid2,
					order_id: order.order_id,
					create_uid: uid
				}).update({
					state: '已退款',
					version: db.command.inc(1)
				});
			}
		}
	
		// 修改订单为已回滚分销订单
		res.updateRes = await db.collection('usemall-order')
			.where({
				order_id: dbcmd.in(orderIds)
			})
			.update({
				is_fxs_rollback: 1,
				last_modify_time: nowdate,
				last_modify_uid: 'job-day'
			});
	}
	
	return res;
}
// 多商品订单
const fxsOrderRollback2 = async (ip) => {
	const nowdate = Date.now();
	const res = {
		detail: {
			count: 0
		},
		count: 0
	};
	
	const orderRes = await db.collection('usemall-order')
		.aggregate()
		.lookup({
			from: 'usemall-order-detail',
			localField: 'order_id',
			foreignField: 'order_id',
			as: 'details'
		})
		.match({
			// 已付款
			order_pay_state: '已付款',
			// 分销订单
			is_fxs: '是',
			// 未结算
			is_settlement: '否',
			// 订单数量
			order_total_cnt: db.command.gt(1),
			// 佣金大于0
			order_fxs_amount: db.command.gt(0),
			// 未回滚
			is_fxs_rollback: db.command.exists(false),
			details: {
				// 已售后
				aftersale_state: 2
			}
		})
		.project({
			order_id: true,
			state: true,
			order_pay_state: true,
			order_refund_state: true,
			create_uid: true,
			is_fxs: true,
			is_fxs_rollback: true,
			is_settlement: true,
			order_fxs_uid: true,
			order_fxs_amount: true,
			order_fxs_uid2: true,
			order_fxs_amount2: true,
			details: {
				order_id: true,
				goods_id: true,
				goods_name: true,
				goods_img: true,
				goods_num: true,
				goods_price: true,
				goods_sku_id: true,
				goods_sku: true,
				goods_sku_name: true,
				aftersale_state: true,
				is_fxs: true,
				is_fxs_rollback: true,
				fxs_amount: true,
				fxs_amount2: true,
				goods_amount: true,
				aftersale_id: true,
				aftersale: true
			}
		})
		.limit(300)
		.end();
	
	
	if (orderRes.data && orderRes.data.length > 0) {
		res.count = orderRes.data.length;
	
		const orderIds = [];
		let fxsRecordUpdateRes = {};
		
		for (let i = 0; i < orderRes.data.length; i++) {
			const order = orderRes.data[i];
			
			// 下单人
			const uid = order.create_uid;
			
			for (let j = 0; j < order.details.length; j++) {
				const orderDetail = order.details[i];
				if (orderDetail.is_fxs !== '是') {
					// 不是分销商品
					continue;
				}
				if (orderDetail.is_fxs_rollback) {
					// 已处理过回滚
					continue;
				}
				if (!(orderDetail.aftersale_state == 2 && ['退款', '退货'].includes(orderDetail.aftersale.type))) {
					// 非完成退款、退货的售后订单
					continue;
				}
				
				
				if (order.order_fxs_uid && orderDetail.fxs_amount) {
					// 上级
					
					// 1. 扣减待结佣金
					await db.collection('usemall-distributor').doc(order.order_fxs_uid).update({
						fxs_unsettled_amount: db.command.inc(-orderDetail.fxs_amount)
					});
					
					// 2. 修改扣减数据、状态
					fxsRecordUpdateRes = await db.collection('usemall-distributor-record').where({
						fxs_uid: order.order_fxs_uid,
						order_id: order.order_id,
						create_uid: uid,
						profit_amount: orderDetail.fxs_amount
					}).update({
						state: orderDetail.aftersale.type,
						version: db.command.inc(1)
					});
					
					if (!fxsRecordUpdateRes.updated) {
						await db.collection('usemall-distributor-record').where({
							fxs_uid: order.order_fxs_uid,
							order_id: order.order_id,
							create_uid: uid,
							profit_amount: db.command.gt(orderDetail.fxs_amount)
						}).update({
							profit_amount: db.command.inc(-orderDetail.fxs_amount),
							version: db.command.inc(1)
						});
					}
				}
				
				if (order.order_fxs_uid2 && orderDetail.fxs_amount2) {
					// 上上级
					
					// 1. 扣减待结佣金
					await db.collection('usemall-distributor').doc(order.order_fxs_uid2).update({
						fxs_unsettled_amount: db.command.inc(-orderDetail.fxs_amount2)
					});
					
					// 2. 修改扣减数据、状态
					fxsRecordUpdateRes = await db.collection('usemall-distributor-record').where({
						fxs_uid: order.order_fxs_uid2,
						order_id: order.order_id,
						create_uid: uid,
						profit_amount: orderDetail.fxs_amount2
					}).update({
						state: orderDetail.aftersale.type,
						version: db.command.inc(1)
					});
					
					if (!fxsRecordUpdateRes.updated) {
						await db.collection('usemall-distributor-record').where({
							fxs_uid: order.order_fxs_uid2,
							order_id: order.order_id,
							create_uid: uid,
							profit_amount: db.command.gt(orderDetail.fxs_amount2)
						}).update({
							profit_amount: db.command.inc(-orderDetail.fxs_amount2),
							version: db.command.inc(1)
						});
					}
				}
				
				// 已回滚
				orderDetail.is_fxs_rollback = 1;
				
				res.detail.count++;
			}
			
			// 分销订单明细 == 已回滚数，则记录整个订单完成回滚
			if (order.details.filter(x => x.is_fxs === '是').length == order.details.filter(x => x.is_fxs_rollback === 1).length) {
				// 修改订单为已回滚分销订单
				await db.collection('usemall-order')
					.where({
						order_id: dbcmd.in(orderIds)
					})
					.update({
						is_fxs_rollback: 1,
						last_modify_time: nowdate,
						last_modify_uid: 'job-day'
					});
					
				res.count++;
			}
		}
	
	}
	
	return res;
}

// 同步微信发货 - 1充值
const doSyncWxDelivery1 = async (ip) => {
	let count = 0;
	let res = {};
	
	const configRes = await db.collection('usemall-wallet-parameter').get();
	const [config = {}] = configRes.data;
	
	if (!config.syncWx) {
		console.log('充值未开启同步微信发货');
		return;
	}
	
	do {
		// 同步微信发货 - 1充值
		res = await syncWxDelivery1(ip, config);
		count += res.count;
	} while (res.count >= 300)
	
	return count;
}
const syncWxDelivery1 = async (ip, config) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	const payRes = await db.collection('usemall-member-pay')
		.where({
			// 已付款
			pay_state: '已付款',
			// 需同步微信发货
			wx_delivery: 1,
			// 未同步
			wx_delivery_sync: 0
		})
		.field({
			pay_title: true,
			pay_openid: true,
			pay_no: true
		})
		.limit(300)
		.get();
	
	if (payRes.data && payRes.data.length > 0) {
		res.count = payRes.data.length;
	
		for (let i = 0; i < payRes.data.length; i++) {
			const pay = payRes.data[i];
			
			// 同步虚拟发货
			const wxres = await wxmpapi.upload_shipping_info({
				order_key: {
					// 2、使用微信支付单号
					order_number_type: 2,
					// 原支付交易对应的微信订单号
					transaction_id: pay.pay_no
				},
				// 发货模式，发货模式枚举值：1、UNIFIED_DELIVERY（统一发货）
				delivery_mode: 1,
				// 发货列表
				shipping_list: [
					{
						// 商品信息
						item_desc: pay.pay_title
					}
				],
				// 3、虚拟商品，虚拟商品
				logistics_type: 3,
				// 上传时间
				upload_time: new Date().toISOString(),
				// 支付者，支付者信息
				payer: {
					// 用户标识，用户在小程序appid下的唯一标识
					openid: pay.pay_openid
				}
			});
			
			// 修改为已同步
			await db.collection('usemall-member-pay')
				.where({
					_id: pay._id
				})
				.update({
					wx_delivery_sync: 1,
					wx_delivery_res: wxres,
					last_modify_time: nowdate,
					last_modify_uid: 'job-day'
				});
		}
	}
	
	return res;
}


// 同步微信发货 - 2开通会员
const doSyncWxDelivery2 = async (ip) => {
	let count = 0;
	let res = {};
	
	const configRes = await db.collection('usemall-member-parameter').get();
	const [config = {}] = configRes.data;
	
	// 会员配置
	if (!config.syncWx) {
		console.log('会员未开启同步微信发货');
		return;
	}
	
	do {
		// 同步微信发货 - 2开通会员
		res = await syncWxDelivery2(ip, config);
		count += res.count;
	} while (res.count >= 300)
	
	return count;
}
const syncWxDelivery2 = async (ip, config) => {
	const nowdate = Date.now();
	const res = {
		count: 0
	};
	
	const payRes = await db.collection('usemall-member-paying')
		.where({
			// 已付款
			pay_state: '已付款',
			// 需同步微信发货
			wx_delivery: 1,
			// 未同步
			wx_delivery_sync: 0
		})
		.field({
			pay_title: true,
			pay_openid: true,
			pay_no: true
		})
		.limit(300)
		.get();
	
	if (payRes.data && payRes.data.length > 0) {
		res.count = payRes.data.length;
	
		for (let i = 0; i < payRes.data.length; i++) {
			const pay = payRes.data[i];
			
			// 同步虚拟发货
			const wxres = await wxmpapi.upload_shipping_info({
				order_key: {
					// 2、使用微信支付单号
					order_number_type: 2,
					// 原支付交易对应的微信订单号
					transaction_id: pay.pay_no
				},
				// 发货模式，发货模式枚举值：1、UNIFIED_DELIVERY（统一发货）
				delivery_mode: 1,
				// 发货列表
				shipping_list: [
					{
						// 商品信息
						item_desc: pay.pay_title
					}
				],
				// 3、虚拟商品，虚拟商品
				logistics_type: 3,
				// 上传时间
				upload_time: new Date().toISOString(),
				// 支付者，支付者信息
				payer: {
					// 用户标识，用户在小程序appid下的唯一标识
					openid: pay.pay_openid
				}
			});
			
			// 修改为已同步
			await db.collection('usemall-member-paying')
				.where({
					_id: pay._id
				})
				.update({
					wx_delivery_sync: 1,
					wx_delivery_res: wxres,
					last_modify_time: nowdate,
					last_modify_uid: 'job-day'
				});
		}
	}
	
	return res;
}



/**
 * 将 UTC+0 转换为 UTC+8
 */
function toDateUTC8(date) {
	if (uniCloud.$provider == 'alipay') {
		// 支付宝云，默认为 UTC+8
		return date;
	}
	
	// 小时 UTC+0 转换为 UTC+8
	date.setHours(date.getHours() + 8);
	return date;
}